using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;
 

public partial class JobSeekers_JobsList : System.Web.UI.Page
{
    string typeName = "";
    string startValue = "";
   
    string typeUrl = "";
    string connectionString = "";

    int itemPerPage = 15;
    int pagePerSeggment = 5;
    
    void RegisterJavaScript()
    {
        Common common = new Common();
        this.ClientScript.RegisterClientScriptBlock(this.GetType(), "openWindow" + this.GridView1.ID, common.CreateScriptForPrint(this.GridView1.ID));
        this.btnPrint.Attributes.Add("onclick", "openWindow" + this.GridView1.ID + "('" + GridView1.ID.ToString() + "',400,700);return false;");
        
    }
    protected void Page_Load(object sender, EventArgs e)
    {

        connectionString =
         WebConfigurationManager.ConnectionStrings[
           "RecruitVietnam"].ConnectionString;
        RegisterJavaScript();
        typeName = Request.QueryString.Get("type");
        if (!IsPostBack)
        {
            ViewState["SortDirection"] = "ASC";
            startValue = Request.QueryString.Get("value");
            typeUrl = Request.QueryString.Get("page");
            if(typeName == null || typeName == "") 
                typeName = "Time";
            if (startValue == null || startValue == "") 
                startValue = "0";
            this.btnBack.Attributes.Add("onclick", 
            "window.open('" + typeUrl + 
            "', target='_main');return false;");
            if (startValue != null && startValue != "")
            {
                litStartValue.Text = startValue;                 
                
                litUrl.Text = typeUrl;
                ShowResult(startValue, typeName, 0);
            }
        }
        else
        {
            startValue = litStartValue.Text;                      
            typeUrl = litUrl.Text;
        }
        if(typeName.ToLower() == "time")
        {
            PostDate(startValue);
        }
        else             
            {
                ExperienceYear(startValue);
            }
       CreateNavigation(Convert.ToInt32(
       literalPages.Text), Convert.ToInt32(
       literalCurrentPage.Text), itemPerPage,
       pagePerSeggment, this.panelNavigation);
    }
    void ExperienceYear(string startValue)
    {
        switch (startValue)
        {
        case "0":
            litType.Text = "Jobs require 0-1 year experience";
            break;
        case "1":
            litType.Text = "Jobs require 1-2 years experience";
            break;
        case "2":
            litType.Text = "Jobs require 2-5 years experience";
            break;
        case "5":
            litType.Text = "Jobs require 5-10 years experience";
            break;
        case "10":
            litType.Text = "Jobs require 10-15 years experience";
            break;
        case "15":
            litType.Text = "Jobs require >15 years experience";
            break;
        }
    }
    void PostDate(string startValue)
    {
        switch (startValue)
        {
            case "0":
                litType.Text = "All jobs";
                break;
            case "1":
                litType.Text = "Jobs by Today";
                break;
            case "5":
                litType.Text = "Jobs in past 5 days";
                break;
            case "10":
                litType.Text = "Jobs in past 10 days";
                break;
            case "30":
                litType.Text = "Jobs in past 30 days";
                break;
            case "60":
                litType.Text = "Jobs in past 60 days";
                break;
        }
    }
    void CreateNavigation(
    int totalPages, int currentPage,
    int itemPerPage, int pagePerSeggent,
    Panel panelLinks)
    {
        panelLinks.Controls.Clear();
        int startPageNo = 0; int endPageNo = 0; int seggmentNo = 0;
        if (totalPages > 1)
        {
            seggmentNo = currentPage / pagePerSeggent;
            if ((currentPage % pagePerSeggent) > 0) seggmentNo += 1;
            startPageNo = pagePerSeggent * (seggmentNo - 1) + 1;
            if (seggmentNo * pagePerSeggent > totalPages)
                endPageNo = totalPages;
            else
                endPageNo = seggmentNo * pagePerSeggent;


            LinkButton linkButton;
            Label labelSpace;

            if (seggmentNo > 1)
            {
                linkButton = new LinkButton();
                linkButton.Text = "First";
                linkButton.Click += new EventHandler(linkButton_Click);
                linkButton.ID = (1).ToString();
                labelSpace = new Label();
                labelSpace.Text = "&nbsp; ";
                panelLinks.Controls.Add(linkButton);
                panelLinks.Controls.Add(labelSpace);
            }

            if (currentPage > pagePerSeggent)
            {
                linkButton = new LinkButton();
                linkButton.Text = "Previous";
                linkButton.Click += new EventHandler(linkButton_Click);
                linkButton.ID = (startPageNo - 1).ToString();
                labelSpace = new Label();
                labelSpace.Text = "&nbsp; ";
                panelLinks.Controls.Add(linkButton);
                panelLinks.Controls.Add(labelSpace);
            }
            int i = 0;
            for (i = startPageNo; i <= endPageNo; i++)
            {
                linkButton = new LinkButton();
                linkButton.Text = i.ToString();

                linkButton.ID = i.ToString();
                if (i == currentPage)
                    linkButton.BackColor = System.Drawing.Color.Aqua;
                linkButton.Click += new EventHandler(linkButton_Click);
                labelSpace = new Label();
                labelSpace.Text = "&nbsp; ";
                panelLinks.Controls.Add(linkButton);
                panelLinks.Controls.Add(labelSpace);
            }
            if (seggmentNo * pagePerSeggent < totalPages)
            {
                linkButton = new LinkButton();
                linkButton.Text = "Next";
                linkButton.ID = (i).ToString();
                linkButton.Click += new EventHandler(linkButton_Click);
                labelSpace = new Label();
                labelSpace.Text = "&nbsp; ";
                panelLinks.Controls.Add(linkButton);
                panelLinks.Controls.Add(labelSpace);
            }
            if (seggmentNo * pagePerSeggent + 1 < totalPages)
            {
                linkButton = new LinkButton();
                linkButton.Text = "Last";
                linkButton.ID = totalPages.ToString();
                linkButton.Click += new EventHandler(linkButton_Click);
                labelSpace = new Label();
                labelSpace.Text = "&nbsp;";
                panelLinks.Controls.Add(linkButton);
                panelLinks.Controls.Add(labelSpace);
            }
        }
    }
    void linkButton_Click(object sender, EventArgs e)
    {

        LinkButton linkButton = (LinkButton)sender;

        int nextPage = 0;
        nextPage = Convert.ToInt32(linkButton.ID);
        literalCurrentPage.Text = nextPage.ToString();
        int endJobs = nextPage * Convert.ToInt32(itemPerPage);
        if (endJobs > Convert.ToInt32(literalTotal.Text)) endJobs = Convert.ToInt32(literalTotal.Text);
        literalRecords.Text = " - Display job: " + (nextPage - 1) * itemPerPage + " -> " + endJobs.ToString();

        ShowResult(startValue, typeName, nextPage - 1);


    }
    DataTable GetDataTable(string startValue, string typeName, int firstRecord)
    {
        SqlServerProvider sqlServerProvider = new SqlServerProvider();
        sqlServerProvider.ConnectionString = connectionString;
        
        sqlServerProvider.ParameterCollection = new string[1] { "@Value"};
        sqlServerProvider.ValueCollection = new string[1] { startValue};
        sqlServerProvider.CommandType = CommandType.StoredProcedure;
        if (firstRecord == 0)
        {
            if (typeName.ToLower() == "time")
                sqlServerProvider.CommandText = "SPTotalJobListByTime";
            else
                sqlServerProvider.CommandText = "SPTotalJobListByExperience";           
            literalTotal.Text = sqlServerProvider.ExecuteScalar().ToString();
            ShowTotalPages(Convert.ToInt32(literalTotal.Text));
        }
        if (typeName.ToLower() == "time")
            sqlServerProvider.CommandText = "SPJobListByTime";
        else
            sqlServerProvider.CommandText = "SPJobListByExperience";
        DataTable dataTable = sqlServerProvider.GetDataTable(firstRecord * itemPerPage, itemPerPage);
        return dataTable;
    }
    DataView GetDataView(string startValue, string typeName, string columnName, string sortType, int firstRecord)
    {
        SqlServerProvider sqlServerProvider = new SqlServerProvider();
        sqlServerProvider.ConnectionString = connectionString;
        if (typeName.ToLower() == "time")
            sqlServerProvider.CommandText = "SPJobListByTime";
        else
            sqlServerProvider.CommandText = "SPJobListByExperience";
        sqlServerProvider.ParameterCollection = new string[1] { "@Value"};
        sqlServerProvider.ValueCollection = new string[1] { startValue };
        sqlServerProvider.CommandType = CommandType.StoredProcedure;
        DataTable dataTable = sqlServerProvider.GetDataTable(firstRecord * itemPerPage, itemPerPage);
        DataView dataView = new DataView(dataTable);
        dataView.Sort = columnName + " " + sortType;
        return dataView;
    }
    void ShowTotalPages(int totalRecords)
    {

        int totalPages = totalRecords / itemPerPage;
        if (totalRecords % itemPerPage != 0)
            totalPages++;
        literalPages.Text = totalPages.ToString();
    }
    void ShowHide(bool flag)
    {
        literalTotal.Visible = flag;
        literalCurrentPage.Visible = flag;
        literalOfText.Visible = flag;
        literalPageText.Visible = flag;
        literalTotalText.Visible = flag;
        literalRecords.Visible = flag;
        literalPages.Visible = flag;
    }
    void ShowResult(string startValue, string typeName, int firstRecord)
    {
        try
        {
            GridViewHelper gridViewHelper = new GridViewHelper();
            gridViewHelper.FillDataTableToGridView(
            GetDataTable(startValue, typeName, firstRecord),
            this.GridView1); ;
            FillUrl(this.GridView1, typeUrl);
            if (GridView1.Rows.Count == 0)
            {
                litError.Text = "Job not found.";
                ShowHide(false);
            }
            else
            {
                ShowHide(true);

                litError.Text = "";
                int currentRecords = Convert.ToInt32(literalCurrentPage.Text);
                litError.Text = "";
                literalRecords.Text =
                " - Display job: " +
                ((currentRecords - 1) * itemPerPage + 1).ToString()
                + "-";
                if ((currentRecords - 1) * itemPerPage + itemPerPage < Convert.ToInt32(literalTotal.Text))
                    literalRecords.Text +=
                    ((currentRecords - 1) * itemPerPage +
                    itemPerPage).ToString();
                else
                    literalRecords.Text += literalTotal.Text;
                literalRecords.Text += " of " + literalTotal.Text;
            }
            CreateNavigation(Convert.ToInt32(
                       literalPages.Text), Convert.ToInt32(
                       literalCurrentPage.Text), itemPerPage,
                       pagePerSeggment, this.panelNavigation);
        }
        catch (Exception ex)
        {
            litError.Text = ex.Message;
        }
    }
    void ShowResult(string startValue, string typeName, string columnName, string sortType, int firstRecord)
    {
        try
        {
            GridViewHelper gridViewHelper = new GridViewHelper();
            gridViewHelper.FillDataViewToGridView(
            GetDataView(startValue, typeName, columnName, sortType, firstRecord),
            this.GridView1); ;
            FillUrl(this.GridView1, typeUrl);
            if (GridView1.Rows.Count == 0)
                litError.Text = "Job not found.";
            else
                litError.Text = "";
        }
        catch (Exception ex)
        {
            litError.Text = ex.Message;
        }
    }
    void FillUrl(GridView GridView1, string backUrl)
    {
        foreach (GridViewRow gridViewRow in GridView1.Rows)
        {
            HyperLink hyperLinkField =
            (HyperLink)gridViewRow.Cells[1].Controls[0];
            hyperLinkField.NavigateUrl =
           hyperLinkField.NavigateUrl + "&page=" + backUrl;
        }
    }
     

    protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
    {
        ShowResult(startValue, typeName, 
        e.SortExpression, ViewState["SortDirection"].ToString(), 
        Convert.ToInt32(literalCurrentPage.Text) - 1);
        if (ViewState["SortDirection"].ToString() == "ASC")
            ViewState["SortDirection"] = "DESC";
        else
            ViewState["SortDirection"] = "ASC";
    }
}
